import 'package:flutter/material.dart';
import 'package:body_measurement/common/global.dart';
import 'package:body_measurement/common/measuring_api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _passwordVisibility = false;

  @override
  void initState() {
    if (Global.userInfo != null) {
      _usernameController.text = Global.userInfo!.mobilephone;
    }
    super.initState();
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Center(
          child: FractionallySizedBox(
            widthFactor: 0.4,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text(
                  '美尔雅量体系统',
                  style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.w400),
                ),
                _buildUsernameInput(),
                _buildPasswordInput(),
                const Padding(padding: EdgeInsets.only(top: 10.0)),
                _buildLoginButton(context),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUsernameInput() {
    /*
    return _buildInputTextField(
      TextInputType.text,
      controller: _usernameController,
      decoration: InputDecoration(
        hintText: '输入账号',
        icon: const Icon(Icons.person, size: 20.0),
        suffixIcon: GestureDetector(
          onTap: () {
            setState(() {
              _username = '';
              _usernameController.clear();
            });
          },
          child: Offstage(
            offstage: _username == '',
            child: const Icon(Icons.clear),
          ),
        ),
        border: InputBorder.none,
      ),
      onChanged: (value) {
        setState(() {
          _username = value;
        });
      },
    );
    */
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0),
      child: TextFormField(
        controller: _usernameController,
        decoration: const InputDecoration(
          hintText: '请输入账号',
          icon: Icon(Icons.person, size: 20.0),
        ),
        keyboardType: TextInputType.text,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入账号！';
          }

          return null;
        },
      ),
    );
  }

  Widget _buildPasswordInput() {
    /*
    return _buildInputTextField(
      TextInputType.text,
      controller: _passwordController,
      decoration: InputDecoration(
        hintText: '输入密码',
        icon: const Icon(Icons.lock, size: 20.0),
        suffixIcon: GestureDetector(
          onTap: () {
            setState(() {
              _password = '';
              _passwordController.clear();
            });
          },
          child: Offstage(
            offstage: _password == '',
            child: const Icon(Icons.clear),
          ),
        ),
        border: InputBorder.none,
      ),
      obscureText: true,
    );
    */

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10.0),
      child: TextFormField(
        controller: _passwordController,
        decoration: InputDecoration(
          hintText: '请输入密码',
          icon: const Icon(Icons.lock, size: 20.0),
          suffixIcon: IconButton(
            icon: Icon(_passwordVisibility ? Icons.visibility_off : Icons.visibility),
            onPressed: () {
              setState(() {
                _passwordVisibility = !_passwordVisibility;
              });
            },
          ),
        ),
        keyboardType: TextInputType.text,
        obscureText: !_passwordVisibility,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入密码！';
          }

          return null;
        },
      ),
    );
  }

  Widget _buildLoginButton(BuildContext context) {
    return Container(
      height: 50.0,
      width: 400.0,
      margin: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: ElevatedButton(
        style: ButtonStyle(
          foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
          backgroundColor: MaterialStateProperty.all<Color>(Theme.of(context).primaryColor),
        ),
        onPressed: () {
          handleLogin(context);
        },
        child: const Text('登录', style: TextStyle(fontSize: 20.0)),
      ),
    );
  }

  void handleLogin(BuildContext context) async {
    if (_formKey.currentState!.validate()) {
      try {
        var res = await MeasuringApi().login(_usernameController.text, _passwordController.text);
        if (res.errcode == 0) {
          Global.userInfo = res.result.userInfo;
          Navigator.of(context).pushReplacementNamed('/', arguments: res.result.userInfo!.truename);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('登录失败：${res.message}')));
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }
  }
}
